﻿# -*- coding:utf-8 -*-
#
# склад
#
import math
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError, AppCommand, NoArgsCommand
from django.db.models.loading import get_app, get_model



class Command( NoArgsCommand ):

    help = 'Import department from Sklad app to SHM  app.'
    requires_model_validation = True
    
    def handle_noargs(self, **options):
        from django.db.models import get_models
        # Выполнение всех операций в одной транзакции
        from django.db import transaction
        transaction.enter_transaction_management()
        try:
            transaction.managed(True)
            self.set_part_unit()
            self.set_department()
            self.set_document()
            transaction.commit()
        finally:
            transaction.rollback()
            transaction.leave_transaction_management()            


        
    def set_part_unit(self):    
        print "Import part unit..."
        skiped = 0
        affected = 0 
        Part = get_model('sklad', 'Part')
        Waybill = get_model('sklad', 'Waybill')
        part = Part.objects.all()
        for p in part:
            waybills = Waybill.objects.filter(doc='rec', part=p)
            if len(waybills) > 0:
                waybill = list(waybills)[0]
                Part.objects.filter(id=p.id).update(unit=waybill.unit)
                affected = affected + 1
            else:
                Part.objects.filter(id=p.id).update(unit=1)
                skiped = skiped + 1
        print 'Part skiped ( never register in waybill ) - %s' % skiped
        print 'Part affected - %s' % affected        
        print 'Part all - %s' %  (affected + skiped )

        
        
    def set_department(self):    
        print "Import department..."
        skiped = 0
        affected = 0 
        DepartmentSklad = get_model('sklad', 'Departmentex')
        DepartmentShm = get_model('shm', 'Department')
        Employee = get_model('shm', 'Employee')
        Phone = get_model('shm', 'Phone')
        departmentsklad = DepartmentSklad.objects.all()
        for item in departmentsklad:
            phone = Phone(number=item.phone)
            phone.save()
            departmentshm = DepartmentShm(id=item.id, parent=None, name=item.name)
            departmentshm.save()
            departmentshm.phone.add(phone)
            departmentshm.save()
            #
            name=[]
            name1=''
            name2=''
            name3=''
            name = item.boss.split(' ',3)
            l = len(name)
            if l == 1:
                name1 = name[0]
            if l == 2:
                name1 = name[0]
                name2 = name[1]
            if l == 3:
                name1 = name[0]
                name2 = name[1]
                name3 = name[2]
            #
            employee = Employee(department = departmentshm, name1=name1,  name2=name2,  name3=name3, boss=True)
            employee.save()
            employee.phone.add(phone)
            employee.save()
            affected = affected + 1    

        print 'Department import - %s' % affected  

 

    def set_document(self):
        print "Import waybill to document..."
        rec_cnt = 0
        del_cnt = 0
        skiped = 0
        Document = get_model('sklad', 'Document')
        DocumentItem = get_model('sklad', 'DocumentItem')
        DocumentReceipt = get_model('sklad', 'DocumentReceipt')
        DocumentDelivery = get_model('sklad', 'DocumentDelivery')
        Waybill = get_model('sklad', 'Waybill')   
        
        waybill = Waybill.objects.all()
        for item in waybill:
        
            if item.doc == 'rec':
                document = Document(kind='R', name='Поступление', date=item.data, date_reg=item.data, user=item.user, state='R', comment=item.description)
                document.save()
                documentreceipt = DocumentReceipt(document=document, indocument=item.description)
                documentreceipt.save()
                rec_cnt = rec_cnt + 1
            elif item.doc == 'del':
                document = Document(kind='D', name='Выдача', date=item.data, date_reg=item.data, user=item.user, state='R', comment=item.description)
                document.save()
                documentdelivery = DocumentDelivery(document=document, department=item.department, phone=item.phone, person=item.person)
                documentdelivery.save()
                del_cnt = del_cnt + 1
            else:
                print "#%s - waybill ignore! doc=%s" % (item.id, item.doc)
                skiped = skiped + 1 
            documentitem = DocumentItem(document=document, part=item.part, quantity=math.fabs(item.count), inventory='')
            documentitem.save()
            
            item.document = document
            item.save()
            
            from django.db import connection, transaction
            cursor = connection.cursor()
            # Data modifying operation - commit required
            cursor.execute("UPDATE sklad_document SET date = %s WHERE id = %s", [item.data, document.id])
            transaction.commit_unless_managed()
       
        print 'Documents receipt  - %s' % rec_cnt
        print 'Documents delivery - %s' % del_cnt        
        print 'Documents skiped   - %s' % skiped
        print 'Documents create   - %s' % (skiped + rec_cnt + del_cnt)
        
            